package com.ruoyi.petrol.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import io.lettuce.core.GeoArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisCommands;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.petrol.domain.ChePetrol;
import com.ruoyi.petrol.service.IChePetrolService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 加油站信息Controller
 * 
 * @author ruoyi
 * @date 2025-01-02
 */
@RestController
@RequestMapping("/petrol")
public class ChePetrolController extends BaseController
{
    @Autowired
    private IChePetrolService chePetrolService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String GEO_KEY = "petrol_stations:"; // Redis中存储加油站Geo数据的key

//  找附近的加油站  按距离排序
//    @RequiresPermissions("petrol:petrol:list")
    @GetMapping("/listAround")
    public TableDataInfo listAround(@RequestParam("longitude") String longitude,
                                    @RequestParam("latitude") String latitude,
                                    @RequestParam("dt") String dt,
                                    @RequestParam("id") Long id)
    {
        //  以经纬度为中心，半径为10km的圆，用作后续搜索的条件
        Circle within = new Circle(new Point(Double.valueOf(longitude), Double.valueOf(latitude)) , new Distance(Double.valueOf(dt), Metrics.KILOMETERS));


        // 查找附近的加油站
        GeoResults<RedisGeoCommands.GeoLocation<String>> radius = redisTemplate.opsForGeo().radius(
                GEO_KEY+id, within,
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().sortAscending().includeDistance());//  搜索规则

        //  将redis中排序完成的数据保存到Map集合中
        List<HashMap<String,Double>> rs = new ArrayList<>();
        radius.forEach(r -> {
            String name = r.getContent().getName();
//            System.out.println(name);
            double distance = r.getDistance().getValue()*1000;
            HashMap<String, Double> mp = new HashMap<>();
            mp.put(name,distance);
            rs.add(mp);
        });

        return getDataTable(rs);

    }


    @RequiresPermissions("petrol:petrol:list")
    @GetMapping("/listGeo/{id}/{name}")
    public TableDataInfo listGeo(@PathVariable(value = "id") Long id)
    {
        startPage();
        ChePetrol cp = new ChePetrol();
        List<ChePetrol> list = chePetrolService.selectChePetrolList(cp);

//        list.forEach(System.out::println);

        if(id!=null){
            redisTemplate.delete(GEO_KEY+id);
            //  创建Geo,将所有的加油站数据放到Redis里面去
            GeoOperations<String, String> geoOps = redisTemplate.opsForGeo();
            for (ChePetrol chePetrol1 : list) {
                //  将经纬度和加油站的id作为识别放入Redis
                if(chePetrol1.getLongitude()!=null && chePetrol1.getLatitude()!=null) {
                    geoOps.add(GEO_KEY + id, new Point(chePetrol1.getLongitude(), chePetrol1.getLatitude()), String.valueOf(chePetrol1.getId()));
                }
            }
        }else{
            return null;
        }

        return getDataTable(list);
    }


    /**
     * 查询加油站信息列表
     */
    @RequiresPermissions("petrol:petrol:list")
    @GetMapping("/list")
    public TableDataInfo list(ChePetrol chePetrol)
    {
        startPage();
        List<ChePetrol> list = chePetrolService.selectChePetrolList(chePetrol);

        return getDataTable(list);
    }

    /**
     * 导出加油站信息列表
     */
    @RequiresPermissions("petrol:petrol:export")
    @Log(title = "加油站信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ChePetrol chePetrol)
    {
        List<ChePetrol> list = chePetrolService.selectChePetrolList(chePetrol);
        ExcelUtil<ChePetrol> util = new ExcelUtil<ChePetrol>(ChePetrol.class);
        util.exportExcel(response, list, "加油站信息数据");
    }

    /**
     * 获取加油站信息详细信息
     */
    @RequiresPermissions("petrol:petrol:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(chePetrolService.selectChePetrolById(id));
    }

    /**
     * 新增加油站信息
     */

    @RequiresPermissions("petrol:petrol:add")
    @Log(title = "加油站信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ChePetrol chePetrol)
    {
        return toAjax(chePetrolService.insertChePetrol(chePetrol));
    }

    /**
     * 修改加油站信息
     */
    @RequiresPermissions("petrol:petrol:edit")
    @Log(title = "加油站信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ChePetrol chePetrol)
    {
        return toAjax(chePetrolService.updateChePetrol(chePetrol));
    }

    /**
     * 删除加油站信息
     */
    @RequiresPermissions("petrol:petrol:remove")
    @Log(title = "加油站信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(chePetrolService.deleteChePetrolByIds(ids));
    }
}
